/*
 * Copyright 2011-2012 Rivoli team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.rivoli.builder.configuration

import com.googlecode.rivoli.RivoliException
import com.googlecode.rivoli.configuration.Configurable
import com.googlecode.rivoli.configuration.Configuration

class ConfigurationBuilder {
	private Configuration configuration

	private ConfigurationBuilder() {
		configuration = new Configuration()
	}

	def invokeMethod(String name, args) {
		if (args.length == 0) {
			throw new RivoliException('no type was provided for the configurable')
		}

		Configurable configurable = createConfigurable(args[-1])
		configurable.init(getParameters(args))

		configuration.addConfigurable(name, configurable)
	}

	private Configurable createConfigurable(Class<?> configurableType) {
		try {
			return configurableType.newInstance()
		} catch (exception) {
			throw new RivoliException("configurable '${configurableType}' could not be created", exception)
		}
	}

	private Map<String, ?> getParameters(args) {
		Map<String, ?> parameters

		if (args.length == 1) {
			parameters = [:]
		} else if (args[0] in Map) {
			parameters = args[0]
		} else {
			throw new RivoliException("parameters should be of type map, not of type ${args[0].class.name}")
		}

		parameters
	}

	static Configuration build(Closure configurationClosure) throws RivoliException {
		ConfigurationBuilder builder = new ConfigurationBuilder()

		configurationClosure.delegate = builder
		configurationClosure()

		builder.configuration
	}
}